from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework.permissions import IsAuthenticated
from django.core.paginator import Paginator
from django.db.models import Q
from .models import Role


class RoleListCreateView(APIView):
    permission_classes = [IsAuthenticated]

    def get(self, request):
        """
        获取角色列表
        支持分页和筛选：name、key、status
        """
        # 获取查询参数
        name = request.query_params.get('name', '')
        key = request.query_params.get('key', '')
        status_q = request.query_params.get('status', '')
        page = int(request.query_params.get('page', 1))
        page_size = int(request.query_params.get('page_size', 10))

        # 构建查询条件
        queryset = Role.objects.all()
        
        if name:
            queryset = queryset.filter(name__icontains=name)
        if key:
            queryset = queryset.filter(key__icontains=key)
        if status_q in ['0', '1']:
            queryset = queryset.filter(status=int(status_q))

        # 排序
        queryset = queryset.order_by('-create_time')

        # 分页
        paginator = Paginator(queryset, page_size)
        try:
            page_obj = paginator.page(page)
        except:
            return Response({
                'code': 400, 
                'message': '页码超出范围', 
                'data': {'results': [], 'total': 0, 'page': page, 'page_size': page_size}
            }, status=status.HTTP_400_BAD_REQUEST)

        # 构建响应数据
        roles = [
            {
                'id': r.id,
                'name': r.name,
                'key': r.key,
                'status': r.status,
                'description': r.remark,
                'created_at': r.create_time.strftime('%Y-%m-%d %H:%M:%S'),
                'updated_at': r.update_time.strftime('%Y-%m-%d %H:%M:%S'),
            }
            for r in page_obj
        ]

        return Response({
            'code': 200, 
            'message': '获取成功', 
            'data': {
                'results': roles,
                'total': paginator.count,
                'page': page,
                'page_size': page_size,
                'total_pages': paginator.num_pages
            }
        })

    def post(self, request):
        """
        新增角色
        body: { name, key, status?, description? }
        """
        name = request.data.get('name', '').strip()
        key = request.data.get('key', '').strip()
        status_val = request.data.get('status', 0)
        description = request.data.get('description', '').strip()

        # 验证必填字段
        if not name:
            return Response({'code': 400, 'message': '角色名称不能为空'}, status=status.HTTP_400_BAD_REQUEST)
        
        if not key:
            return Response({'code': 400, 'message': '角色标识不能为空'}, status=status.HTTP_400_BAD_REQUEST)

        # 验证字段长度
        if len(name) > 100:
            return Response({'code': 400, 'message': '角色名称长度不能超过100个字符'}, status=status.HTTP_400_BAD_REQUEST)
        
        if len(key) > 100:
            return Response({'code': 400, 'message': '角色标识长度不能超过100个字符'}, status=status.HTTP_400_BAD_REQUEST)

        # 检查重复
        if Role.objects.filter(name=name).exists():
            return Response({'code': 400, 'message': '角色名称已存在'}, status=status.HTTP_400_BAD_REQUEST)
        
        if Role.objects.filter(key=key).exists():
            return Response({'code': 400, 'message': '角色标识已存在'}, status=status.HTTP_400_BAD_REQUEST)

        try:
            role = Role.objects.create(
                name=name, 
                key=key, 
                status=status_val or 0, 
                remark=description
            )
            
            return Response({
                'code': 200, 
                'message': '角色创建成功', 
                'data': {
                    'id': role.id, 
                    'name': role.name, 
                    'key': role.key, 
                    'status': role.status, 
                    'description': role.remark,
                    'created_at': role.create_time.strftime('%Y-%m-%d %H:%M:%S')
                }
            })
        except Exception as e:
            return Response({'code': 500, 'message': f'创建失败: {str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class RoleDetailView(APIView):
    permission_classes = [IsAuthenticated]

    def get(self, request, role_id: int):
        """
        获取角色详情
        """
        try:
            role = Role.objects.get(id=role_id)
            return Response({
                'code': 200, 
                'message': '获取成功', 
                'data': {
                    'id': role.id,
                    'name': role.name,
                    'key': role.key,
                    'status': role.status,
                    'description': role.remark,
                    'created_at': role.create_time.strftime('%Y-%m-%d %H:%M:%S'),
                    'updated_at': role.update_time.strftime('%Y-%m-%d %H:%M:%S'),
                }
            })
        except Role.DoesNotExist:
            return Response({'code': 404, 'message': '角色不存在'}, status=status.HTTP_404_NOT_FOUND)

    def put(self, request, role_id: int):
        """
        编辑角色
        """
        try:
            role = Role.objects.get(id=role_id)
        except Role.DoesNotExist:
            return Response({'code': 404, 'message': '角色不存在'}, status=status.HTTP_404_NOT_FOUND)

        name = request.data.get('name', '').strip()
        key = request.data.get('key', '').strip()
        status_val = request.data.get('status')
        description = request.data.get('description', '').strip()

        # 验证字段长度
        if name and len(name) > 100:
            return Response({'code': 400, 'message': '角色名称长度不能超过100个字符'}, status=status.HTTP_400_BAD_REQUEST)
        
        if key and len(key) > 100:
            return Response({'code': 400, 'message': '角色标识长度不能超过100个字符'}, status=status.HTTP_400_BAD_REQUEST)

        # 检查重复
        if name and Role.objects.exclude(id=role_id).filter(name=name).exists():
            return Response({'code': 400, 'message': '角色名称已存在'}, status=status.HTTP_400_BAD_REQUEST)
        
        if key and Role.objects.exclude(id=role_id).filter(key=key).exists():
            return Response({'code': 400, 'message': '角色标识已存在'}, status=status.HTTP_400_BAD_REQUEST)

        # 更新字段
        if name:
            role.name = name
        if key:
            role.key = key
        if status_val is not None:
            role.status = int(status_val)
        if description is not None:
            role.remark = description

        try:
            role.save()
            return Response({
                'code': 200, 
                'message': '角色更新成功',
                'data': {
                    'id': role.id,
                    'name': role.name,
                    'key': role.key,
                    'status': role.status,
                    'description': role.remark,
                    'updated_at': role.update_time.strftime('%Y-%m-%d %H:%M:%S')
                }
            })
        except Exception as e:
            return Response({'code': 500, 'message': f'更新失败: {str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    def delete(self, request, role_id: int):
        """
        删除角色
        """
        try:
            role = Role.objects.get(id=role_id)
        except Role.DoesNotExist:
            return Response({'code': 404, 'message': '角色不存在'}, status=status.HTTP_404_NOT_FOUND)

        try:
            # 检查是否有用户关联此角色
            if role.role_users.exists():
                return Response({'code': 400, 'message': '该角色下还有用户，无法删除'}, status=status.HTTP_400_BAD_REQUEST)
            
            role.delete()
            return Response({'code': 200, 'message': '角色删除成功'})
        except Exception as e:
            return Response({'code': 500, 'message': f'删除失败: {str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

